/************************************************************************/
/*																		*/
/*		School Hangover Project											*/
/*																		*/
/*		IMAC 2010														*/
/*		Author : 	Helena Duchaussoy									*/
/*					Isabelle Gouwy										*/
/*					Nathalie Kuoch										*/
/*					Franck Letellier									*/
/*					Louise Pequignot									*/
/*																		*/
/*		E-mail: flo-in-underware@googlegroups.com						*/
/*																		*/
/************************************************************************/

#include "Engine.h"

#include <osgGA/StateSetManipulator>
#include <osgGA/KeySwitchMatrixManipulator>
#include <osgViewer/ViewerEventHandlers>

#include "CameraManipulator.h"



Engine::Engine() {

	m_pcamera = new Camera();

	m_ptimer = new Timer();

	m_lastTime = m_ptimer->getTimer()->tick();
}


void Engine::clear(){
	StageManager::killInstance();

	delete m_pcamera;
	delete m_ptimer;
	m_pcamera = NULL;
}

void Engine::init() {
	// Managers
	StageManager::getInstance().init();
	ObjectManager::getInstance().init();
	DialogManager::getInstance().init();
	
	//Init the viewer
	m_viewer.setUpViewInWindow( 100, 100, 800, 600 );
	m_viewer.setSceneData(StageManager::getInstance().getRootNode());
	
	m_viewer.setCameraManipulator( new osgGA::CameraManipulator());
	m_viewer.addEventHandler( new osgGA::StateSetManipulator(m_viewer.getCamera()->getOrCreateStateSet()) );

    m_viewer.realize();

	StageManager::getInstance().getRootNode()->setUpdateCallback(new UpdateCallback());

	while(!m_viewer.done()) {
		osg::Timer_t current = m_ptimer->getTimer()->tick();
		if(m_ptimer->getTimer()->delta_s(m_lastTime, current) >= (1./FPS)) {
			m_lastTime = current;
			m_viewer.frame();
		}
	}	

}

Timer* Engine::getTimer(){
	return m_ptimer;
}

void Engine::update() {

	// Juste in order to avoid several cal to Get instance in one function
	StageManager & stageManager = StageManager::getInstance();

	if(Engine::getInstance().getTimer()->isRunning() && !Engine::getInstance().getTimer()->isPause()){
		//if the current stage is not over
		if (!stageManager.isFinished()){
			//std::cout << "FRAME NUMBER : " << m_viewer.getFrameStamp()->getReferenceTime()/*getFrameNumber()*/ << std::endl;
			//Update the stage
			stageManager.update();
			//m_ptimer->update();
		}else{
			//Here we'll need to go to the next level
		}
	}
}
